﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Exhibition.Common.Helper;
using Exhibition.Service;

namespace Exhibition.Manage
{
    public partial class DBRestore : BaseAdminPage
    {

        public string path = string.Empty;
        public string startcheck = string.Empty;
        public string load = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            path = Server.MapPath("../databak/");
            //开始统计数据-全部
            if (Request.QueryString["ChcekBakFile"] == "true")
            {
                Response.Write(ChcekBakFile(0, Request.QueryString["filename"]));
                Response.End();
            }

            //开始统计数据-全部
            if (Request.QueryString["RestoreData"] == "true")
            {
                Response.Write(RestoreData());
                Response.End();
            }

            BindData();
        }

        protected void btnRestore_Click(object sender, EventArgs e)
        {
            string[] strFline = null;
            string fileid = this.CheckedIDS.Value;
            List<object> lisDel = grid.GetSelectedFieldValues(new string[] { grid.KeyFieldName });
            if (lisDel.Count > 0) {
                foreach (var obj in lisDel)
                {
                    strFline = File.ReadAllLines(Server.MapPath("../databak/" + obj));

                    if (strFline.Length > 0)
                    {

                        if (strFline[0] == "--@Begin BackUp Data")
                        {
                            this.filename.Value = fileid;
                            this.ShowRestore.Visible = true;
                            this.ShowBakFileList.Visible = false;
                            this.search.Visible = false;
                            startcheck = "CheckBakFile()";
                        }
                        else
                        {
                            JsHelper.Alert(this, "该备份卷不是卷头，无法恢复");
                        }

                    }
                    else
                    {
                        JsHelper.Alert(this, "文件内容为空!");
                    }
                }
            }
           
        }

        protected void btnDel_Click(object sender, EventArgs e)
        {
            //string[] fileids = this.CheckedIDS.Value.Split(',');
            //for (int i = 0; i < fileids.Length; i++)
            //{
            //    File.Delete(path + "\\" + fileids[i].Trim());
            //}
            //BindData();
        }

        private void BindData()
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            if (dir.Exists)
            {
                string[] filenames = Directory.GetFiles(path);

                DataTable dt = new DataTable();
                DataRow dr;
                dt.Columns.Add("Name");
                dt.Columns.Add("ID");
                dt.Columns.Add("Notice");
                dt.Columns.Add("Date");
                dt.Columns.Add("Size");

                foreach (string file in filenames)     //查找子目录   
                {
                    if (Path.GetFileName(file).IndexOf(".txt") >= 0)
                    {
                        dr = dt.NewRow();
                        System.IO.FileInfo objInfo = new System.IO.FileInfo(file);
                        dr["ID"] = Path.GetFileName(file);
                        dr["Name"] = Path.GetFileName(file);
                        string strFline = File.ReadAllLines(Path.GetFullPath(file))[0].ToString().Trim();
                        if (strFline == "--@Begin BackUp Data")
                        {
                            dr["Notice"] = "卷头";
                        }
                        else if (strFline == "--@End BackUp Data")
                        { dr["Notice"] = "卷尾"; }
                        else
                        {
                            dr["Notice"] = "分卷" + Path.GetFileName(file).Replace(".txt", "").Split('_')[2].ToString();

                        }
                        dr["Date"] = objInfo.LastWriteTime;
                        dr["Size"] = objInfo.Length / 1024;
                        dt.Rows.Add(dr);
                    }
                }

                DataView dv = dt.DefaultView;
                dv.Sort = "Name , Date DESC";

                this.grid.DataSource = dv;
                this.grid.DataBind();
            }
        }


        private string ChcekBakFile(int iCount, string filename)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            if (dir.Exists)
            {
                if (File.Exists(path + "/" + filename))
                {
                    string[] strFline = File.ReadAllLines(path + "/" + filename);
                    if (strFline.Length > 0)
                    {
                        if (strFline[0].ToString().Trim() == "--@End BackUp Data")
                            return iCount.ToString();
                        else
                        {
                            string strfilename;
                            if (iCount == 0)
                                strfilename = strFline[1].Replace("--@", "");
                            else
                                strfilename = strFline[0].Replace("--@", "");
                            iCount = iCount + 1;
                            return ChcekBakFile(iCount, strfilename);
                        }
                    }
                }
                else
                {
                    iCount = 0;
                    return "0";
                }
            }
            return iCount.ToString();
        }


        private string RestoreData()
        {
            string filename = Request.QueryString["filename"];
            DirectoryInfo dir = new DirectoryInfo(path);
            string strResult = "";
            if (dir.Exists)
            {
                if (File.Exists(path + "/" + filename))
                {
                    string[] strFline = File.ReadAllLines(path + "/" + filename);
                    if (strFline.Length > 0)
                    {
                        string strLen = string.Empty;
                        
                            strLen = (int.Parse(filename.ToLower().Replace(".txt", "").Split('_')[2].ToString()) + 1).ToString();
                         
                        if (strFline[0].ToString().Trim() == "--@End BackUp Data")
                        {
                            strResult = "$End$" + strLen;
                        }
                        else
                        {
                            strResult = "$" + strFline[0].Replace("--@", "").Trim() + "$" + strLen;
                            if (strFline[0].ToString().Trim() == "--@Begin BackUp Data")
                            {
                                strResult = "$" + strFline[1].Replace("--@", "").Trim() + "$" + strLen;
                            }
                        }
                        strResult = CreateDateBase(path + "/" + filename) + strResult;
                    }
                }
            }
            return strResult;
        }



        private string CreateDateBase(string sqlpath)
        {
            //读取需要执行的SQL卷
            string SqlPath = sqlpath;
            string SqlContent = File.ReadAllText(SqlPath);
            //按行分组一条一条执行
            string[] SqlArray = Regex.Split(SqlContent, @"\r \n");
            string strExecute = string.Empty;

            //创建连接对象
            SqlConnection myDbSqlConnection = new SqlConnection(DBHelper.Db.ConnectionString);
            myDbSqlConnection.Open();

            for (int i = 0; i < SqlArray.Length; i++)
            {
                //执行SQL语句
                strExecute = strExecute + ExecuteSql(SqlArray[i], myDbSqlConnection);
            }

            //关闭连接
            myDbSqlConnection.Close();

            return strExecute;
        }



        /// <summary>
        /// 执行该条SQL语句
        /// </summary>
        /// <param name="p"></param>
        private string ExecuteSql(string sql, SqlConnection myDbSqlConnection)
        {
            string strExecute = string.Empty;

            //为空返回
            if (sql.Trim() == "")
            {
                return strExecute;
            }

            try
            {
                SqlCommand command = new SqlCommand();
                command.Connection = myDbSqlConnection;
                command.CommandText = sql;
                command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                strExecute = e.Message.ToString();
                HttpContext.Current.Response.Write(strExecute + "---" + sql + "<br>");
            }
            return strExecute;
        }

    }
}